﻿namespace TanzimSaqib.NoBrainer
{
    using System.IO;
    using System;

    /// <summary>
    /// Monitors the configuration XML file and performs cache initialization and
    /// refreshing it when underlying content is changed
    /// </summary>
    internal class ContentSentinel
    {
        private static ContentWatcher _Watcher;

        public static void Watch(string cmsXmlDirectory, string fileFilter)
        {
            _Watcher = new ContentWatcher(cmsXmlDirectory, fileFilter);
            _Watcher.OnChangeNotify += _Watcher_OnChangeNotify;
        }

        static void _Watcher_OnChangeNotify(ContentWatcher sender, ContentWatcherEventArgs e)
        {
            CacheManager.Instance.Remove(CacheManager.CmsMvcXml(e.FilePath));
        }
    }

    internal class ContentWatcher
    {
        private readonly string _Directory = string.Empty;
        private readonly string _FileFilter = string.Empty;
        private readonly FileSystemWatcher _Watcher;
        public delegate void ChangeNotify(ContentWatcher sender, ContentWatcherEventArgs e);
        public event ChangeNotify OnChangeNotify;

        public ContentWatcher(string cmsXmlDirectory, string fileFilter)
        {
            _Directory = cmsXmlDirectory;
            _FileFilter = fileFilter;

            _Watcher = new FileSystemWatcher(_Directory, _FileFilter)
            {
                NotifyFilter = NotifyFilters.Attributes
                               | NotifyFilters.CreationTime
                               | NotifyFilters.DirectoryName
                               | NotifyFilters.FileName
                               | NotifyFilters.LastAccess
                               | NotifyFilters.LastWrite
                               | NotifyFilters.Size,
                IncludeSubdirectories = true,
                EnableRaisingEvents = true
            };

            _Watcher.Changed += _Watcher_Changed;
        }

        void _Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            if (OnChangeNotify != null)
            {
                OnChangeNotify(this, new ContentWatcherEventArgs { FilePath = e.FullPath, FileName = e.Name });
            }
        }
    }

    internal class ContentWatcherEventArgs : EventArgs
    {
        public string FileName { get; set; }
        public string FilePath { get; set; }
    }
}
